package com.tssup.fesco.common.utils.sms;

import com.tssup.fesco.common.utils.BeanUtilsHelper;
import com.tssup.fesco.common.utils.HttpClientHelper;
import com.tssup.fesco.common.utils.json.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.Arrays;
import java.util.Map;

/**
 * Created by franco.cheng on 2017/4/12.
 */
@Component
public class SmsUtil {

    private static Logger log = LoggerFactory.getLogger(SmsUtil.class);

    private static String URL = "http://gw.api.taobao.com/router/rest";
    private static String API_METHOD = "alibaba.aliqin.fc.sms.num.send";
    private static String SMS_TYPE = "normal";

    @Value("${sms.alidayu.app.key}")
    private String appKey;

    @Value("${sms.alidayu.sign.name}")
    private String smsFreeSignName;

    @Value("${sms.alidayu.api.secret}")
    private String apiSecret;


    public AliDaYuResult send(String recNum, String smsTemplateCode, String smsTemplateParam) {
        try {
            SmsRequest smsRequest = new SmsRequest();
            smsRequest.setMethod(API_METHOD);
            smsRequest.setAppKey(appKey);
            smsRequest.setSms_type(SMS_TYPE);
            smsRequest.setRec_num(recNum);
            smsRequest.setTimestamp(System.currentTimeMillis() + "");
            smsRequest.setSms_free_sign_name(smsFreeSignName);
            smsRequest.setSms_param(smsTemplateParam);
            smsRequest.setSms_template_code(smsTemplateCode);
            Map<String, Object> params = BeanUtilsHelper.transBean2Map(smsRequest);
            params.put("sign", signTopRequest(params, apiSecret));
            String response =  HttpClientHelper.postForm(URL, params);
            AliDaYuResult smsResult = JsonUtil.toObject(response, AliDaYuResult.class);
            log.debug("【SMS Result " + recNum + ", temp = "+ smsTemplateCode +"】 ----- " + JsonUtil.toJson(smsResult));
            return smsResult;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String signTopRequest(Map<String, Object> params, String secret) throws IOException {
        // 第一步：检查参数是否已经排序
        String[] keys = params.keySet().toArray(new String[0]);
        Arrays.sort(keys);

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder();
        query.append(secret);
        for (String key : keys) {
            String value = (String) params.get(key);
            if (StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)){
                query.append(key).append(value);
            }
        }

        query.append(secret);
        byte[] bytes = encryptMD5(query.toString());

        // 第五步：把二进制转化为大写的十六进制
        return byte2hex(bytes);
    }

    public static String byte2hex(byte[] bytes) {
        StringBuilder sign = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex.toUpperCase());
        }
        return sign.toString();
    }

    public static byte[] encryptMD5(String data) throws IOException {
        return encryptMD5(data.getBytes("UTF-8"));
    }

    public static byte[] encryptMD5(byte[] data) throws IOException {
        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            bytes = md.digest(data);
        } catch (GeneralSecurityException gse) {
            throw new IOException(gse.toString());
        }
        return bytes;
    }

    public String getAppKey() {
        return appKey;
    }

    public void setAppKey(String appKey) {
        this.appKey = appKey;
    }

    public String getSmsFreeSignName() {
        return smsFreeSignName;
    }

    public void setSmsFreeSignName(String smsFreeSignName) {
        this.smsFreeSignName = smsFreeSignName;
    }

    public String getApiSecret() {
        return apiSecret;
    }

    public void setApiSecret(String apiSecret) {
        this.apiSecret = apiSecret;
    }


    public static void main(String[] args) {
        String recNum = "18502079242";
        String loginConfirmCode = "SMS_60960288";
        String loginConfirmParam = "{code:'123456',product:'福立方商城'}";
        SmsUtil smsUtil = new SmsUtil();
        smsUtil.setAppKey("23749091");
        smsUtil.setSmsFreeSignName("\u5468\u884c\u79d1\u6280");
        smsUtil.setApiSecret("fe7246faa2e45c25c64f10ffee236875");
        AliDaYuResult smsResult = smsUtil.send(recNum, loginConfirmCode, loginConfirmParam);
        log.info(JsonUtil.toJson(smsResult));
    }




}
